import logging
import random

from django.db.backends.utils import logger

# Create your views here.
from django import http

from django.views import View
from django_redis import get_redis_connection


from meiduo_mall.utils.response_code import RETCODE
from . import constants
from verifications.libs.captcha.captcha import captcha

# 创建日志输出器
from verifications.libs.yuntongxun.SendMessage import send_message

logger = logging.getLogger('django')

class SMSCodeView(View):
    """短信验证码"""
    def get(self, request, mobile):
        """

        :param request: 请求地址URL
        :param moblie: 手机号
        :return: 返回值
        """
        # 接收参数
        image_code_client = request.GET.get('image_code')
        uuid = request.GET.get('uuid')
        # 校验参数
        if not all([image_code_client, uuid]):
            return http.JsonResponse({'code': RETCODE.NECESSARYPARAMERR, 'errmsg': '缺少必传参数'})
        # 创建redis连接对象
        redis_conn = get_redis_connection('verify_code')
        # 提取图形验证码
        image_code_server = redis_conn.get('img_%s' % uuid)
        if image_code_server is None:
            # 图形验证码过期或者不存在
            return http.JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': '图形验证码失效'})
        # 删除图形验证码，避免恶意测试图形验证码
        try:
            redis_conn.delete('img_%s' % uuid)
        except Exception as e:
            logger.error(e)
        # 对比图形验证码
        image_code_server = image_code_server.decode()
        if image_code_client.lower() != image_code_server.lower():
            return http.JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': '输入图形验证码有误'})
        # 生成短信验证码
        sms_code = '%06d' % random.randint(0,999999)
        logger.info(sms_code)

        # 保存短信验证码
        redis_conn.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        # 调用云通信接口发送短信验证码
        print("测试："+mobile, sms_code, constants.SMS_CODE_REDIS_EXPIRES, constants.SEND_SMS_TEMPLATE_ID)
        send_message(mobile, [sms_code, constants.SMS_CODE_REDIS_EXPIRES], constants.SEND_SMS_TEMPLATE_ID)


        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '发送短信成功'})


class ImageCodeView(View):
    """图形验证码"""
    def get(self, request, uuid):
        """

        :param request: 请求参数
        :param uuid: 用户唯一标识，用于存储来校验图形验证码
        :return: 响应前端
        """
        # 生成图形验证码
        text,image = captcha.generate_captcha()

        # 获取redis数据库连接对象
        redis_conn = get_redis_connection('verify_code')
        # 存储图形验证码
        redis_conn.setex('img_%s' % uuid, 300, text)

        return http.HttpResponse(image, content_type='image/jpg')